import { defineStore } from 'pinia'
import { api, API_TSL_FRONTEND } from 'boot/axios'
import { toRaw } from 'vue'
import { Loading } from 'quasar'

import { useUserStore } from './userStore'

// For QC WO Review Page
export const useMassScanStore = defineStore('massScan', {
  state: () => ({
    // For ScanQR Code (search_order)
    sucWOList: [],
    noPermList: [],
    notExistList: [],
    errorWOList: [],
    workOrderList: [], // all info (record)
    woList: [], // all data (structured)
  }),

  getters: {
    getWorkOrderList: (state) => {
      return state.woList
      // return state.workOrderList
    }

  },
  actions: {

    async loadMassScan (accID, role) { // This role is real role not role group
      Loading.show()
      this.workOrderList = []
      this.woList = []
      console.log('role: ', role)
      try{
        const res = await api.get(API_TSL_FRONTEND + '/OrderOnHold/' + `${accID}/`)
        console.log('MassScan OrderOnHold result: ', res)
        const data = res.data.data
        this.workOrderList = (data.record) ? data.record : []
        console.log('this.workOrderList: ', this.workOrderList)
        if(this.workOrderList){

          this.workOrderList.forEach( wo =>{

            let e = null
            if(wo.history.length > 0){
              e = wo.history[wo.history.length-1]
            }

            // get role action, time
            let act = null
            let actTime = null
            if (role === 'WORKER') {
              let currStatus = (e.worker.actionRecord.length>0)? e.worker.actionRecord[e.worker.actionRecord.length - 1] : ''
              act = currStatus.action.toLowerCase()
              actTime = currStatus.time

            } else if (role === 'QC' || role === 'Teamleader' || role === 'StoneQC') {
              let currStatus = (role === 'QC') ? e.qcCheck : (role === 'Teamleader') ? e.leaderCheck : e.stoneCheck
              // assume all wo are started / complete when shown on MassScanPage
              act = (currStatus.check_time) ? 'complete' : 'start'
              actTime = (act === 'complete') ? currStatus.check_time : currStatus.rec_time

            } else {
              console.log('cannot get role current status info')
            }

            // TODO: show all records 
            let record_temp = [] // records: [{ cnName, dateTime, action }]
            let workerName = null
            for (let i = 0; i < wo.history.length; i++){
              // insert all 
              let hist = toRaw(wo.history[i])
              // worker
              workerName = hist.worker.cnName
              let wac = hist.worker.actionRecord
              wac.forEach(w => {
                record_temp.push({ cnName: workerName, role: '工人', dateTime: w.time, action: (w.action === 'Start') ? '开始' : (w.action === 'Pause') ? '暂停' : '完成' ,  isFailed: null, failDetails: null, remark: null})
              })
              // qcCheck
              let qcName = hist.qcCheck.cnName
              let qcrecTime = hist.qcCheck.rec_time
              let qccheckTime = hist.qcCheck.check_time
              let qcisFailed = hist.qcCheck.failed
              let qcfailReason = hist.qcCheck.fail_detail
              let qcremark = hist.qcCheck.remark
              if (qcrecTime != null) {
                record_temp.push({ cnName: qcName, role: 'QC', dateTime: qcrecTime, action: '开始', isFailed:  null, failDetails: null, remark: null})
              }
              if (qccheckTime != null) {
                record_temp.push({ cnName: qcName, role: 'QC', dateTime: qccheckTime, action: '审核', isFailed:  qcisFailed, failDetails: qcfailReason, remark: qcremark})
              }
              // leaderCheck
              let lcName = hist.leaderCheck.cnName
              let lcrecTime = hist.leaderCheck.rec_time
              let lccheckTime = hist.leaderCheck.check_time
              let lcisFailed = hist.leaderCheck.failed
              let lcfailReason = hist.leaderCheck.fail_detail
              let lcremark = hist.leaderCheck.remark
              if (lcrecTime != null) {
                record_temp.push({ cnName: lcName, role: '组长', dateTime: lcrecTime, action: '开始' , isFailed:  null, failDetails: null, remark: null})
              }
              if (lccheckTime != null) {
                record_temp.push({ cnName: lcName, role: '组长', dateTime: lccheckTime, action: '审核', isFailed:  lcisFailed, failDetails: lcfailReason, remark: lcremark})
              }
              // stoneCheck
              let scName = hist.stoneCheck.cnName
              let screcTime = hist.stoneCheck.rec_time
              let sccheckTime = hist.stoneCheck.check_time
              let scisFailed = hist.stoneCheck.failed
              let scfailReason = hist.stoneCheck.fail_detail
              let scremark = hist.stoneCheck.remark
              if (screcTime !== null) {
                record_temp.push({ cnName: scName, role: '验石', dateTime: screcTime, action: '开始', isFailed:  null, failDetails: null, remark: null })
              }
              if (sccheckTime !== null) {
                record_temp.push({ cnName: scName, role: '验石', dateTime: sccheckTime, action: '审核', isFailed:  scisFailed, failDetails: scfailReason, remark: scremark })
              }
            }
            
            let temp = {
              orderNo: wo.orderNo,
              action: act,
              time: actTime,
              latest_failReasons: '',
              latest_remark: '',
              selected: false,
              records: record_temp
            }

            this.woList.push(temp)
          })
          console.log('this.woList: ', this.woList)
        }
        Loading.hide()
        return true
      }catch (error){
        console.log(error.response)
        Loading.hide()
        return false
      }
    },

    getWorkOrder(orderNo){
      return this.woList.find(wo => wo.orderNo === orderNo)
    },

    async addWO (accID, scanwo) { // ScanQRCode page
      Loading.show()
      const useUser = useUserStore()
      const alreadyExistWo = []
      const notExistWO = []
      this.errorWOList = []

      // Check if it has any duplicates orders from woList 
      scanwo.forEach((swo) => {
        const isDup = this.woList.some((w) => w.orderNo === swo);
        (isDup) ? alreadyExistWo.push(swo) : notExistWO.push(swo)
      })

      const haveDup = alreadyExistWo.length > 0
      // console.log('haveDup:', haveDup)
      // console.log('alreadyExistWo:', alreadyExistWo)
      // console.log('notExistWO:', notExistWO)

      // call API to add workOrder (in notExistWO)
      try {
        const res = await api.post(API_TSL_FRONTEND + '/OrderOnHold/' + `${accID}` + '/search_order/', { orders: notExistWO,source: useUser.currentDept.source })
        console.log("MassScan OrderOnHold/search_order result: ", res)

        this.sucWOList = res.data.data.allowed_list
        this.noPermList = res.data.data.no_perm_list
        this.notExistList = res.data.data.not_exist_list

        // console.log('this.sucWOList: ', this.sucWOList)
        // console.log('this.noPermList: ', this.noPermList)
        // console.log('this.notExistList: ', this.notExistList)

        if(this.sucWOList.length > 0){
          this.sucWOList.forEach( e => this.woList.push({ 
            orderNo: e.order,
            action: 'start',
            time: e.data,
            latest_failReasons:[],
            latest_remark: '',
            selected: false,
            records: []
          }))
        }

        if(this.noPermList.length > 0){
          this.noPermList.forEach( e => this.errorWOList.push({ orderNo: e.order, type: e.error_message}))
        }
        if(this.notExistList.length > 0){
          this.notExistList.forEach( e => this.errorWOList.push({ orderNo: e.order, type: '工单不存在'}))
        }

        console.log('this.errorWOList: ', this.errorWOList)
        Loading.hide()
        return true
      } catch (error) {
        Loading.hide()
        return false
      }
    },

    async changeWOStatus (accID, orderNo, action) {
      Loading.show()
      console.log('accID: '+ accID + ' orderNo: ' + orderNo + ' action: ' + action)
      const useUser = useUserStore()
    
      const act = (action === 'start')? 'Start' : (action === 'pause') ? 'Pause' : (action === 'complete') ? 'Complete' : console.log('error cannot get action') 
      try{
        const res = await api.post(API_TSL_FRONTEND + '/WorkerAction/', { orders: orderNo, account_pk: accID, action: act})
        console.log("MassScan WorkerAction result: ",res)
        // Update WO Record
        const woData = res.data.data.orders[0]
        let woIdx = this.woList.findIndex(wo => wo.orderNo === orderNo[0])
        console.log('woIdx: ', woIdx)
        console.log("this.woList", this.woList)
        if(woIdx !== -1){
          let temp = {
            cnName: useUser.cnName,
            role: '工人', 
            dateTime: woData.time,
            action: (woData.action === 'Start') ? '开始' : (woData.action === 'Pause') ? '暂停' : '完成',
            isFailed: null, 
            failDetails: null, 
            remark: null
          }
          this.woList[woIdx].records.push(temp)
          console.log("this.woList", this.woList)
      }
        console.log('change wolist: ', this.woList)
        Loading.hide()
        return true
      }catch (error){
        this.errorWOList.push(notExistWO[i])
        Loading.hide()
        return false
      }
    },

    initErrorWOList (){
      this.errorWOList = []
    }
  }
})